package cn.tao.base.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

//实现bean的注入
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 1.获取请求头，U-TOKEN
     * 2.如果获取不到直接拦截
     * 3.如果能够拿到，去验证redis中是否过期
     *      1过期直接拦截
     *      2有数据没过期，放行 延时
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取u-token
        String token = request.getHeader("U-TOKEN");
        //token不为空，获取redis中是否有值
        if (token!=null){
            Object o = redisTemplate.opsForValue().get(token);
            if (o!=null){
                //有token，没有过期，一直刷新它的声明周期
                redisTemplate.opsForValue().set(token,o,30, TimeUnit.MINUTES);
                return true;
            }
        }
        //设置响应类型，响应编码
        response.setContentType("application/json;charset=UTF-8");
        //返回json格式数据，让前端接收 前端去跳转到登录页面
        //{"success":false,"message":"noAuth"}
        PrintWriter writer = response.getWriter();
        writer.println("{\"success\":false,\"message\":\"noAuth\"}");
        return false;
    }
}
